﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CM.BL.BC;
using CM.BL.BE;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Collections.Specialized;

namespace WebAppHTML5
{
    public partial class login : System.Web.UI.Page
    {
        string pRetval = string.Empty;
        string usuarioId = string.Empty;
        string password = string.Empty;
        string sessId = string.Empty;
        string idioma = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.HttpMethod.Equals("POST"))
            {
                
            }
            else
            {
                pRetval = "{\"success\":{0}, \"errors\":{\"reason\": \"{1}\"}, ";
                pRetval += "\"lstItemsResale\":{2}, \"user\":{3} ";
                pRetval += "}";

                usuarioId = Request.Params["usuario"] != null ? Request.Params["usuario"].ToString() : "";
                password = Request.Params["clave"] != null ? Request.Params["clave"].ToString() : "";
                idioma = Request.Params["idioma"] != null ? Request.Params["idioma"].ToString() : "";

                string retval = loginWeb(); retval = retval.Trim();
                if (!string.IsNullOrEmpty(retval))
                {
                    pRetval = pRetval.Replace("{0}", "false");
                    pRetval = pRetval.Replace("{1}", retval);
                    pRetval = pRetval.Replace("{2}", "[]");
                }
                else
                {
                    pRetval = pRetval.Replace("{0}", "true");
                    pRetval = pRetval.Replace("{1}", retval);
                    string list = getItemsResale();
                    pRetval = pRetval.Replace("{2}", list);
                }
            }

            Response.ContentType = "application/json; charset=UTF-8";
            Response.Write(pRetval);
        }

        private string loginWeb()
        {
            string retval = string.Empty;
            RfcConfigParametersBE objConn = new RfcConfigParametersBE();

            try
            {
                string strUname, strPswd;
                strUname = usuarioId.Trim(); strPswd = password.Trim();
                if (!string.IsNullOrEmpty(strUname) && !string.IsNullOrEmpty(strPswd))
                {
                    objConn.Id = (Guid.NewGuid()).ToString();
                    sessId = objConn.Id;
                    objConn.Passwd = strPswd;
                    objConn.Uname = strUname;

                    NameValueCollection param = new NameValueCollection(); //@@@
                    param.Add("Id", objConn.Id);
                    param.Add("UserId", strUname);
                    param.Add("PwdId", strPswd);

                    CredencialesController.cargarInfo(param); //(SIEMPRE)@@@
                    retval = HelperBC.getConnectionId(objConn);
                    if (objConn != null)
                    {
                        string json = JsonConvert.SerializeObject(objConn);
                        pRetval = pRetval.Replace("{3}", json);
                    }
                    else
                    {
                        pRetval = pRetval.Replace("{3}", "[]");
                    }
                }
                else
                {
                    retval = "Debe ingresar todos los campos requeridos.";
                    pRetval = pRetval.Replace("{3}", "[]");
                }
            }
            catch (Exception ex)
            {
                retval = ex.Message;
            }
            finally
            {
                retval = retval.ToUpper().IndexOf("TIMEDOUT") >= 0 || retval.ToUpper().IndexOf("TIMEOUT") >= 0 ? "No se pudo establecer la conexión con el servidor." : retval;
            }
            return retval;
        }

        private string getItemsResale()
        {
            string retval = string.Empty, message = string.Empty;
            string Json = "";
            List<SolicitudPedidoBE> lstPO = new List<SolicitudPedidoBE>();
            retval = SolicitudPedidoBC.getInstance(sessId).getItemsForRelease(out lstPO);
            if (lstPO != null || lstPO.Count > 0)
            {
                Json = JsonConvert.SerializeObject(lstPO);
            }
            else
            {
                Json = "[]";
            }
            return Json;
        }

        private void checkLogin()
        {
            //_objConn = (RfcConfigParametersBE)Session["objConn"];
            //if (_objConn == null)
            //{
            //    Response.Redirect("Default.aspx");
            //}
        }
    }
}
